﻿using System;
using LB.Common;
using LB.Server.Common;
using LB.Server.DAL;

namespace LB.Server.Core
{
    public class UserManagement : IUserManagement
    {
        private readonly ApplicationLog log = new ApplicationLog();
        private readonly IUserRepository userRepository;

        public UserManagement(IUserRepository userRepository)
        {
            this.userRepository = userRepository;
        }

        public LoginToken Login (string login, string hash)
        {
            if (!userRepository.IsLoginExist(login))
                return null;
            var user = userRepository.GetUserBylogin(login);

            var savedSessions = userRepository.GetWorkingSessionsByUserId(user.UserId);

            // close all previously opened sessions
            savedSessions.ForEach(ss=> userRepository.CloseSession(ss.SessionId));

            var sessionDuration = new TimeSpan(0, 0, ServerConfiguration.SessionConfiguration.DefultDuration);
            var token = new LoginToken(user.ToCommonUser(), sessionDuration);

            var session = userRepository.CreateSession(token.SessionId, token.User.UserId, token.StartTime, token.SessionDuration);

            return session != null ? token : null;
        }

        public bool CreateAccount(string login, string password)
        {
            log.WriteTrace("Create new user invoked");

            if (userRepository.IsLoginExist(login))
                return false;

            if (userRepository.CreateAccount(login, password))
            {
                log.WriteError("Account was created successfully.");
                return true;
            }
            
            log.WriteError("Can't create account {0}", login);
            return false;
        }

        public bool IsLoginExist(string login)
        {
            return userRepository.IsLoginExist(login);
        }

        public bool IsSessionActive(string sessionId)
        {
            var session = userRepository.IsSessionExist(sessionId);
            if (session == null)
                return false;
            return session.StartTime + session.SessionDuration > DateTime.Now;
        }

        public void LogOut(string sessionId)
        {
            userRepository.CloseSession(sessionId);
        }
    }
}